import React from 'react';
import { Button, Modal, DatePicker, Menu } from "antd";
import MyEchart from '../components/myEchart';
import jQuery from 'jquery';
import ReactEcharts from 'echarts-for-react';
import Moment from "moment";
import moduleNavImg from "../imgs/ksh33.png";

const globalConfig = require("../js/globalConfig");
const globalOption = require("../js/optionConfig");
const utils = require("../js/utils");
const fft = require("../js/fft/fft");

class NowVib extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            //true--主井 false--副井
            flag: true,
            //0--电机 1--卷筒左轴承座 2--卷筒右轴承座 3--导向轮
            index: 0,
            url: this.props.flag ? globalConfig.url + "/getMainVibration" : globalConfig.url + "/getSubVibration",
            xData: new Array(20).fill(0),
            yData: new Array(20).fill(0),
            option: {
                yAxis: [{ name: "振动(μm)" }],
                xAxis: [{ name: "时间" }],
                series: [{
                    name: "振动",
                    symbol: "circle",
                    type: 'line',
                    //smooth: "true",
                    itemStyle: {
                        normal: {
                            color: '#fff',
                            lineStyle: { color: '#91cc75' }
                        }
                    }
                }]
            }
        };
    }

    updateChart(chartInstance) {
        var this_ = this;
        jQuery.ajax({
            url: this_.state.url,
            dataType: "JSON",
            type: "POST",
            data: {},
            success: function (result) {
                // result解析 
                // var data = new Array(4).fill(0);
                // data[0] = result.data_1;
                // data[1] = result.data_2;
                // data[2] = result.data_3;
                // data[3] = result.data_4;

                let newXData = this_.state.xData.slice();
                let newYData = this_.state.yData.slice();
                newXData.push(Moment(new Date()).format("HH:mm:ss"));
                //newYData.push(data[this_.state.index]);
                newYData.push(Math.random());
                newXData.shift();
                newYData.shift();

                this_.setState({
                    xData: newXData,
                    yData: newYData
                });

                utils.setOption(chartInstance, newXData, newYData);
            }
        });
    }

    clearChart(instance) {
        instance.clear();
        instance.setOption(globalOption.options.baseOption);
        instance.setOption(globalOption.options.secPageOption);
        instance.setOption(this.state.option);
        this.setState({
            xData: new Array(20).fill(0),
            yData: new Array(20).fill(0),
        });
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (this.state.flag == nextProps.flag && this.state.index == nextProps.index)
            return false;
        this.setState({
            flag: nextProps.flag,
            index: nextProps.index
        })
        let instance = this.echartsReact.getEchartsInstance();
        this.clearChart(instance);
        return true;
    }

    componentDidMount() {
        let instance = this.echartsReact.getEchartsInstance();
        instance.setOption(globalOption.options.secPageOption);
        instance.setOption(this.state.option);
        this.timerID = setInterval(() => {
            this.updateChart(instance);
        }, 500);
    }

    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    render() {
        return (
            <ReactEcharts ref={e => { this.echartsReact = e; }} option={globalOption.options.baseOption} style={{ height: "100%", width: "100%" }} opts={{ renderer: 'svg' }} />
        );
    }
}

class TodayVib extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            //true--主井 false--副井
            flag: true,
            //0--电机 1--卷筒左轴承座 2--卷筒右轴承座 3--导向轮
            index: 0,
            url: this.props.flag ? globalConfig.url + "/getMainVibration" : globalConfig.url + "/getSubVibration",
            option: {
                yAxis: [{ name: "振动(μm)" }],
                xAxis: [{ name: "小时(h)" }],
                series: [{
                    name: "振动",
                    symbol: "none",
                    type: 'line',
                    //smooth: "true",
                    itemStyle: {
                        normal: {
                            color: '#91cc75',
                            lineStyle: { color: '#91cc75' }
                        }
                    }
                }]
            }
        };
    }

    updateChart(chartInstance) {
        var this_ = this;
        jQuery.ajax({
            url: this_.state.url,
            dataType: "JSON",
            type: "POST",
            data: {},
            success: function (result) {
                // result解析 
                // let xData=[];
                // let yData = new Array(4).fill(null);
                // for (let i = 0; i < 4; i++)
                //     yData[i] = [];
                // for (var i = 0; i < result.length; i--) {
                //     xData.push(result[i].timeStamp);
                //     yData[0][i].push(result[i].data_1);
                //     yData[1][i].push(result[i].data_2);
                //     yData[2][i].push(result[i].data_3);
                //     yData[3][i].push(result[i].data_4);
                // }

                let xData = [];
                let yData = [];


                var hour = new Date().getHours();
                for (let i = 0; i < hour; i++) {
                    for (let j = 0; j < 5; j++) {
                        xData.push(i + (1 / 5) * j);
                        yData.push(Math.random());
                    }
                }

                utils.setOption(chartInstance, xData, yData);
            }
        });
    }

    clearChart(instance) {
        instance.clear();
        instance.setOption(globalOption.options.baseOption);
        instance.setOption(globalOption.options.secPageOption);
        instance.setOption(this.state.option);
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (this.state.flag == nextProps.flag && this.state.index == nextProps.index)
            return false;
        this.setState({
            flag: nextProps.flag,
            index: nextProps.index
        })
        let instance = this.echartsReact.getEchartsInstance();
        this.clearChart(instance);
        this.updateChart(instance);
        return true;
    }

    componentDidMount() {
        let instance = this.echartsReact.getEchartsInstance();
        instance.setOption(globalOption.options.secPageOption);
        instance.setOption(this.state.option);
        this.updateChart(instance);
    }

    render() {
        return (
            <ReactEcharts ref={e => { this.echartsReact = e; }} option={globalOption.options.baseOption} style={{ height: "100%", width: "100%" }} opts={{ renderer: 'svg' }} />
        );
    }
}

class VibFreq extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            //true--主井 false--副井
            flag: true,
            //0--电机 1--卷筒左轴承座 2--卷筒右轴承座 3--导向轮
            index: 0,
            url: this.props.flag ? globalConfig.url + "/getMainVibration" : globalConfig.url + "/getSubVibration",
            option: {
                yAxis: [{ name: "信号强度" }],
                xAxis: [{
                    name: "频率(Hz)",
                    axisLabel: {
                        interval: 5,
                        //showMaxLabel: true
                    }
                }],
                series: [{
                    name: "信号强度",
                    symbol: "circle",
                    type: 'line',
                    areaStyle: {},
                    itemStyle: {
                        normal: {
                            color: '#eb2f96',
                            lineStyle: { color: '#eb2f96' }
                        }
                    }
                }]
            }
        };
    }

    updateChart(chartInstance) {
        var this_ = this;
        jQuery.ajax({
            url: this_.state.url,
            dataType: "JSON",
            type: "POST",
            data: {},
            success: function (result) {
                let yData = [];
                let fs = 2;
                let L = 100;
                for (let i = 0; i < L; i++) {
                    yData.push(Math.random());
                }
                const res = utils.getFreq(fs, yData);
                utils.setOption(chartInstance, res[0], res[1]);
            }
        });
    }

    clearChart(instance) {
        instance.clear();
        instance.setOption(globalOption.options.baseOption);
        instance.setOption(globalOption.options.secPageOption);
        instance.setOption(this.state.option);
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (this.state.flag == nextProps.flag && this.state.index == nextProps.index)
            return false;
        this.setState({
            flag: nextProps.flag,
            index: nextProps.index
        })
        let instance = this.echartsReact.getEchartsInstance();
        this.clearChart(instance);
        this.updateChart(instance);
        return true;
    }

    componentDidMount() {
        let instance = this.echartsReact.getEchartsInstance();
        instance.setOption(globalOption.options.secPageOption);
        instance.setOption(this.state.option);
        this.timerID = setInterval(() => {
            this.updateChart(instance);
        }, 1000);
    }

    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    render() {
        return (
            <ReactEcharts ref={e => { this.echartsReact = e; }} option={globalOption.options.baseOption} style={{ height: "100%", width: "100%" }} opts={{ renderer: 'svg' }} />
        );
    }
}

class DaySelect extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            //true--主井 false--副井
            flag: this.props.flag,
            //0--电机 1--卷筒左轴承座 2--卷筒右轴承座 3--导向轮
            index: 0,
            beginDate: this.props.beginDate,
            url: this.props.flag ? globalConfig.url + "/getMainVibration" : globalConfig.url + "/getSubVibration",
            option: {
                xAxis: [{ name: "采样点" }],
                yAxis: [{ name: "振动(μm)" }],
                series: [
                    {
                        symbol: "circle",
                        name: "振动",
                        type: 'line'
                    },
                ]
            }
        };
    }

    updateChart(url, beginDate, chartInstance) {
        jQuery.ajax({
            url: url,
            dataType: "JSON",
            type: "POST",
            data: {
                date: beginDate
            },
            success: function (result) {
                let xData = [];
                let yData = [];
                for (let i = 0; i < 24; i++) {
                    for (let j = 0; j < 20; j++) {
                        xData.push(i + (1 / 20) * j);
                        yData.push(Math.random());
                    }
                }
                utils.setOption(chartInstance, xData, yData);
            }
        });
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (nextProps.beginDate === this.state.beginDate || nextProps.beginDate === "")
            return false;
        this.setState({
            beginDate: nextProps.beginDate
        });
        this.updateChart(this.state.url, nextProps.beginDate, this.echartsReact.getEchartsInstance());
        return true;
    }

    componentDidMount() {
        let instance = this.echartsReact.getEchartsInstance();
        instance.setOption(this.state.option);
        this.updateChart(this.state.url, this.props.beginDate, instance);
    }

    render() {
        return (
            <ReactEcharts ref={e => { this.echartsReact = e; }} option={globalOption.options.modelOption} style={{ height: "100%", width: "100%" }} opts={{ renderer: 'svg' }} />
        );
    }
}

class VibPage extends React.Component {
    constructor(props) {
        super(props);
        //获取<Link/>传递的参数
        let flag = this.props.location.state.flag;
        this.state = {
            //true--主井 false--副井
            flag: flag,
            //0--电机 1--卷筒左轴承座 2--卷筒右轴承座 3--导向轮
            index: 0,
            infoVisible: false,
            isDayVisible: false,
            isDayEnable: false,
            beginDate: "",
            mainCurrent: "1",
            subCurrent: "1"
        };
    }
    onChange(date, dateString) {
        console.log(dateString);
        this.setState({
            beginDate: dateString,
            infoVisible: false
        });
    }

    dayHandleOk() {
        if (this.state.beginDate.length <= 0) {
            this.setState({
                infoVisible: true,
                isDayEnable: false
            });
        } else {
            this.setState({
                infoVisible: false,
                isDayEnable: true
            });
        }
    }
    dayHandleClose() {
        this.setState({
            isDayVisible: false,
            infoVisible: false,
            isDayEnable: false
        });
    }
    dayShowModal() {
        this.setState({
            isDayVisible: true,
        });
    }
    render() {
        const { mainCurrent } = this.state;
        const { subCurrent } = this.state;
        return (
            <div className="my-lay-all page-home">
                {/* <nav className="page-nav" id="vib-fir-nav">
                    <div className="left-btns">
                        <Button className="page-btn" ghost onClick={() => { this.setState({ flag: true }); }}>主井信息</Button>
                        <Button className="page-btn" ghost onClick={() => { this.setState({ flag: false }); }}>副井信息</Button>
                    </div>
                </nav> */}
                <Menu theme="dark" mode="horizontal" selectedKeys={[mainCurrent]} className="page-nav-2">
                    <Menu.Item key="1" onClick={() => { this.setState({ flag: true, mainCurrent: "1" }); }}>
                        主井信息
                    </Menu.Item>
                    <Menu.Item key="2" onClick={() => { this.setState({ flag: false, mainCurrent: "2" }) }}>
                        副井信息
                    </Menu.Item>
                </Menu>

                <Menu theme="dark" mode="horizontal" selectedKeys={[subCurrent]} className="page-nav-2" id="vib-nav">
                    <Menu.Item key="1" onClick={() => { this.setState({ index: 0, subCurrent: "1" }); }}>
                        电机
                    </Menu.Item>
                    <Menu.Item key="2" onClick={() => { this.setState({ index: 1, subCurrent: "2" }); }}>
                        卷筒左轴承座
                    </Menu.Item>
                    <Menu.Item key="3" onClick={() => { this.setState({ index: 2, subCurrent: "3" }); }}>
                        卷筒右轴承座
                    </Menu.Item>
                    <Menu.Item key="4" onClick={() => { this.setState({ index: 3, subCurrent: "4" }); }}>
                        导向轮
                    </Menu.Item>
                </Menu>




                <div className="page-context">
                    <div className="con-module">
                        <div className="c-m-main my-module-3">
                            <nav>
                                <div className="curve-link">当前振动</div>
                                <img src={moduleNavImg} alt=""></img>
                            </nav>
                            <div>
                                <NowVib flag={this.state.flag} index={this.state.index} />
                            </div>
                        </div>
                    </div>
                    <div className="con-module">
                        <div className="c-m-main my-module-3">
                            <nav>
                                <div className="curve-link">本日振动</div>
                                <img src={moduleNavImg} alt=""></img>
                            </nav>
                            <div>
                                <TodayVib flag={this.state.flag} index={this.state.index} />
                            </div>
                        </div>
                    </div>
                    <div className="con-module">
                        <div className="c-m-main my-module-3">
                            <nav>
                                <div className="curve-link">振动频谱</div>
                                <img src={moduleNavImg} alt=""></img>
                            </nav>
                            <div>
                                <VibFreq flag={this.state.flag} index={this.state.index} />
                            </div>
                        </div>
                    </div>
                </div>
                <nav className="page-nav">
                    <div className="right-btns">
                        <Button className="page-btn" ghost onClick={() => this.dayShowModal()}>按日查询</Button>
                        <Modal title="按日查询" visible={this.state.isDayVisible} width={800}
                            onCancel={() => this.dayHandleClose()}
                            footer={[
                                <Button key="submit" type="default" onClick={() => this.dayHandleClose()}>取消</Button>,
                                <Button key="submit" type="primary" onClick={() => this.dayHandleOk()}>查询</Button>
                            ]}
                        >
                            <span style={{ marginRight: 10 }}>请选择日期</span>
                            <DatePicker onChange={(date, dateString) => this.onChange(date, dateString)} />
                            {this.state.infoVisible ? <span style={{ marginLeft: 10 }}>请选择查询日期！</span> : <span />}
                            {this.state.isDayEnable ? <div className="modelChart"><DaySelect beginDate={this.state.beginDate} flag={this.state.flag} /></div> : <div />}
                        </Modal>
                    </div>
                </nav>
            </div>
        );
    }
}

export default VibPage;